All files soundmeter.js

3.44% Statements 1/29
0% Branches 0/8
0% Functions 0/6
3.44% Lines 1/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71        1x                                                                                                                                    
'use strict';
 
import "./external/loglevel.min.js";
 
const Logger = window.log;
 
export class SoundMeter {
	/**
	 * 
	 * @param {AudioContext} context 
	 */
	constructor(context, volumeMeterUrl) {
		this.context = context;
    	this.instant = 0.0;
		this.mic = null;
		this.volumeMeterNode = null;
		this.url  = volumeMeterUrl;
	}
	/**
	 * 
	 * @param {MediaStream} stream 
	 * @param {Function} levelCallback 
	 * @param {Function} errorCallback 
	 * @returns 
	 */
	connectToSource(stream, levelCallback, errorCallback) {
	  return this.context.audioWorklet.addModule(this.url).then(()=> {
			this.mic = this.context.createMediaStreamSource(stream);
	        this.volumeMeterNode = new AudioWorkletNode(this.context, 'volume-meter');
 
 
	        this.volumeMeterNode.port.onmessage = (event) => {
				if (event.data.type == 'debug') {
					Logger.debug(event.data.message);
				}
				else {
	            	this.instant = event.data;
	            	levelCallback(this.instant.toFixed(2));
					Logger.debug("Audio level: " + this.instant.toFixed(2));
 
				}
	        };
 
	        this.mic.connect(this.volumeMeterNode);
		})
        .catch((err) => {
            if (errorCallback !== undefined) {
                errorCallback(err);
            }
			Logger.error("Error in soundmeter: " + err);
			Logger.error("You may need to define the url of the volume-meter-processor.js");
            throw err;
        });
	}
 
	stop() {
 
		if (this.volumeMeterNode != null) {
			this.volumeMeterNode.port.postMessage('stop');
			this.volumeMeterNode.disconnect();
			this.volumeMeterNode.port.close();
			this.volumeMeterNode = null;
		}
		if (this.mic != null) {
			this.mic.disconnect();
			this.mic = null;
		}
	}
 
}